/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function (root) {
  const queue = []
  let front = 0, rear = 0, depth = 0
  let levelLoc
  let isLeaf = false
  if (root != null) {
    queue[++rear] = root
    depth++
  }
  levelLoc = rear  // 每层结束的位置
  while (front < rear) {
    let p = queue[++front]
    if (p.left != null) {
      queue[++rear] = p.left
    }
    if (p.right != null) {
      queue[++rear] = p.right
    }
    if (!isLeaf) {
      if (p.left == null && p.right == null) return depth
    }
    if (front == levelLoc) {
      depth++
      if (isLeaf) return depth
      levelLoc = rear
    }
  }
  return depth
}